package com.zhilei.intercept;

import com.google.gson.Gson;
import com.zhilei.base.BaseInfoProperties;
import com.zhilei.pojo.Admin;
import com.zhilei.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 使用本地线程变量获取数据
 *
 * @author 志磊
 * @data 2024-09-05
 */
@Slf4j
public class JWTCurrentUserInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    public static ThreadLocal<Users> USER_THREAD = new ThreadLocal<>();
    public static ThreadLocal<Admin> ADMIN_THREAD = new ThreadLocal<>();

    /**
     * 根据本地线程获取详细信息
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String appUserJson = request.getHeader(APP_USER_JSON);
        String saasUserJson = request.getHeader(SAAS_USER_JSON);
        String adminUserJson = request.getHeader(ADMIN_USER_JSON);

        if (StringUtils.isNotBlank(appUserJson)) {
            // 对appUserJson进行编码
            appUserJson = URLDecoder.decode(appUserJson, StandardCharsets.UTF_8.toString());
            Users appUser = new Gson().fromJson(appUserJson, Users.class);
            USER_THREAD.set(appUser);
        }

        if (StringUtils.isNotBlank(saasUserJson)) {
            saasUserJson = URLDecoder.decode(saasUserJson, StandardCharsets.UTF_8.toString());
            Users saasUser = new Gson().fromJson(saasUserJson, Users.class);
            USER_THREAD.set(saasUser);
        }

        if (StringUtils.isNotBlank(adminUserJson)) {
            adminUserJson = URLDecoder.decode(adminUserJson, StandardCharsets.UTF_8.toString());
            Admin admin = new Gson().fromJson(adminUserJson, Admin.class);
            ADMIN_THREAD.set(admin);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 关闭本地线程链接
        USER_THREAD.remove();
        ADMIN_THREAD.remove();
    }
}
